package subject;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashSet;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import subject.ISubject;

public class Subject extends UnicastRemoteObject implements ISubject, ActionListener {

	private static final long serialVersionUID = 1L;
	private HashSet<String> clients;
	private String name;
	private JFrame frame;
	private JTextField textSendfield;
	private JButton sendBoutton;
	private JTextArea textDisplayArea;
	private JTextArea listClients;

	public Subject(String name) throws RemoteException {
		super();
		this.name= name;
		clients = new HashSet<String>();
		
		frame=new JFrame(name);
		build();
	}


	private void build() {
		frame.setBounds(100, 100, 603, 401);
		frame.getContentPane().setLayout(new BorderLayout());
		JPanel buttonPane = new JPanel();
		buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
		frame.getContentPane().add(buttonPane, BorderLayout.SOUTH);

		 sendBoutton = new JButton("Envoyer");
		sendBoutton.addActionListener(this);
		textDisplayArea = new JTextArea();
		textSendfield = new JTextField();
		buttonPane.add(textSendfield);
		textSendfield.setColumns(45);
		buttonPane.add(sendBoutton);
		frame.getRootPane().setDefaultButton(sendBoutton);
		 frame.getContentPane().add(textDisplayArea, BorderLayout.CENTER);

		
		
		listClients = new JTextArea();
		listClients.setRows(15);
		listClients.setColumns(12);
		frame.getContentPane().add(listClients, BorderLayout.WEST);
		frame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		frame.setVisible(true);
		
	}


	public synchronized void diffuser(String from, JTextField message)
			throws RemoteException {

	}

	public HashSet<String> getClients() {
		return clients;
	}

	public synchronized void addClient(String nameClient) {
		if (!clients.contains(nameClient)) {
			clients.add(nameClient);
		}
	}

	public String getName() {
		return name;
	}

	public synchronized void removeClient(String nameClient) {
		if (!clients.contains(nameClient)) {
			clients.remove(nameClient);
		}
	}

	public void diffuser(String from, String message) throws RemoteException {
		if (!textSendfield.getText().equals("")) {
			textDisplayArea.append( textSendfield.getText() + "\n");
			textSendfield.setText("");
		}

	}

	public void actionPerformed(ActionEvent e) {
		try {
			diffuser("toto", textSendfield.getText());
		} catch (RemoteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

}
